package com.fin.quant.common;

import cn.hutool.core.collection.CollectionUtil;
import com.fin.quant.common.vo.DividendVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;

import java.util.Comparator;
import java.util.List;

public class DividendUtil {
    /**
     * 获取最近完整一年的分红
     *
     * @param dividendHistoryList
     * @return
     */
    public static Pair<Double, Integer> getYearDividendPerShare(List<DividendVO> dividendHistoryList) {
        if (CollectionUtil.isEmpty(dividendHistoryList)) {
            return null;
        }
        // 按财务年度倒序排列
        dividendHistoryList.sort(Comparator.comparing(DividendVO::getFiscalYear).reversed()
                .thenComparing((DividendVO d) -> "年度分红".equals(d.getFrequency()) ? 0 : 1));

        // 获取最新的分红记录
        DividendVO latestDividend = dividendHistoryList.get(0);

        // 判断最新分红是否为中期分红
        if (StringUtils.equalsAny(latestDividend.getFrequency(), "Quarterly", "中期分红")) {
            // 如果是中期分红，则取上一年度的分红总和
            Integer previousYear = latestDividend.getFiscalYear() - 1;
            return Pair.of(calculateYearTotalDividend(dividendHistoryList, previousYear), previousYear);
        } else {
            // 如果是年度分红，则取当前年度的分红总和
            Integer latestYear = latestDividend.getFiscalYear();
            return Pair.of(calculateYearTotalDividend(dividendHistoryList, latestYear), latestYear);
        }
    }


    /**
     * 计算指定年份的分红总和
     *
     * @param dividendHistoryList 分红历史列表
     * @param year                指定年份
     * @return 该年份的分红总和
     */
    private static double calculateYearTotalDividend(List<DividendVO> dividendHistoryList, Integer year) {
        double totalDividend = 0;
        for (DividendVO dividend : dividendHistoryList) {
            if (dividend.getFiscalYear().equals(year)) {
                if (dividend.getAmountPerShare() != null) {
                    totalDividend += dividend.getAmountPerShare().doubleValue();
                }
            }
        }
        return totalDividend;
    }
}
